package org.dbstar.scheduler.serializer;

import java.io.File;
import java.util.Properties;

/**
 * PropertySerializable辅助类
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-9
 */
public class PropertySerializeHelper {
	private final Properties properties;

	private final String parent;

	public PropertySerializeHelper(Properties properties, String parent) {
		super();
		this.properties = properties;
		this.parent = parent;
	}

	private String getPropertyName(String name) {
		return parent == null ? name : (parent + '.' + name);
	}

	public void write(String name, int value) {
		properties.setProperty(getPropertyName(name), String.valueOf(value));
	}

	public void write(String name, long value) {
		properties.setProperty(getPropertyName(name), String.valueOf(value));
	}

	public void write(String name, boolean value) {
		properties.setProperty(getPropertyName(name), String.valueOf(value));
	}

	public int readInt(String name, int defaultValue) {
		return Integer.valueOf(properties.getProperty(getPropertyName(name), String.valueOf(defaultValue)));
	}

	public long readLong(String name, long defaultValue) {
		return Long.valueOf(properties.getProperty(getPropertyName(name), String.valueOf(defaultValue)));
	}

	public boolean readBoolean(String name, boolean defaultValue) {
		return Boolean.valueOf(properties.getProperty(getPropertyName(name), String.valueOf(defaultValue)));
	}

	public void write(String name, String value) {
		if (value != null) {
			properties.setProperty(getPropertyName(name), value);
		}
	}

	public String read(String name, String defaultValue) {
		return properties.getProperty(getPropertyName(name), defaultValue);
	}

	public String read(String name) {
		return properties.getProperty(getPropertyName(name));
	}

	public void write(String name, PropertySerializable value) throws Throwable {
		if (value != null) {
			String propertyName = getPropertyName(name);
			properties.setProperty(propertyName + ".class", value.getClass().getName());
			value.serialize(new PropertySerializeHelper(properties, propertyName));
		}
	}

	public PropertySerializable readSerializable(String name) throws Throwable {
		String propertyName = getPropertyName(name);
		String className = properties.getProperty(propertyName + ".class");
		if (className != null) {
			PropertySerializable object = (PropertySerializable) Class.forName(className).newInstance();
			object.deserialize(new PropertySerializeHelper(properties, propertyName));
			return object;
		} else {
			return null;
		}
	}

	public void write(String name, File value) {
		if (value != null) {
			write(name, value.getPath());
		}
	}

	public File readFile(String name) {
		String path = read(name);
		return path == null ? null : new File(path);
	}
}
